<template>
  <view class="container">
    <StatusBar />
    
    <view class="search-bar">
      <view class="search-input">
        <text class="search-icon">🔍</text>
        <input 
          type="text"
          v-model="searchText"
          placeholder="搜索设备名称或ID"
          placeholder-class="placeholder"
        />
      </view>
      <text class="filter-btn" @tap="openFilter">⚙️</text>
    </view>

    <view v-if="hasActiveAlarms" class="alarm-banner" @tap="showAlarmList = true">
      <text class="alarm-icon">⚠️</text>
      <text>当前有{{ activeAlarms.length }}个设备存在报警</text>
      <text class="arrow">></text>
    </view>

    <view class="device-list">
      <view 
        v-for="device in filteredDevices" 
        :key="device.id"
        class="device-card"
        @tap="handleDeviceClick(device)"
      >
        <view class="device-header">
          <view class="device-info">
            <text class="device-name">{{ device.name }}</text>
            <text :class="['status-tag', device.status]">{{ getStatusText(device.status) }}</text>
          </view>
          <text class="device-id">{{ device.id }}</text>
        </view>
        
        <view class="device-data">
          <view 
            v-for="(value, key) in device.data" 
            :key="key"
            class="data-item"
          >
            <text class="label">{{ key }}</text>
            <text class="value">{{ value }}</text>
          </view>
        </view>

        <view v-if="device.alarms.length > 0" class="alarm-list">
          <view 
            v-for="(alarm, index) in device.alarms" 
            :key="index"
            :class="['alarm-item', alarm.type]"
          >
            <text class="alarm-icon">{{ alarm.type === 'error' ? '❌' : '⚠️' }}</text>
            <text class="alarm-message">{{ alarm.message }}</text>
          </view>
        </view>

        <view class="device-footer">
          <text class="update-time">{{ device.lastUpdate }}</text>
        </view>
      </view>
    </view>

    <uv-popup 
      ref="filterPopupRef"
      :show="showFilterPopup" 
      mode="bottom"
      :overlay="true"
      :close-on-click-overlay="true"
      :z-index="10090"
      :duration="300"
      :safe-area-inset-bottom="true"
      :round="10"
      :custom-style="{ backgroundColor: '#FFFFFF' }"
      @close="closeFilter"
    >
      <view class="filter-popup">
        <view class="popup-header">
          <text class="title">筛选</text>
          <text class="close" @tap="closeFilter">✖️</text>
        </view>
        
        <view class="filter-section">
          <text class="section-title">设备类型</text>
          <view class="filter-options">
            <text 
              v-for="type in deviceTypes" 
              :key="type.value"
              :class="['filter-option', { active: filters.type === type.value }]"
              @tap="handleFilterChange('type', type.value)"
            >
              {{ type.label }}
            </text>
          </view>
        </view>

        <view class="filter-section">
          <text class="section-title">设备状态</text>
          <view class="filter-options">
            <text 
              v-for="status in deviceStatus" 
              :key="status.value"
              :class="['filter-option', { active: filters.status === status.value }]"
              @tap="handleFilterChange('status', status.value)"
            >
              {{ status.label }}
            </text>
          </view>
        </view>

        <button class="reset-btn" @tap="resetFilters">重置筛选</button>
      </view>
    </uv-popup>

    <uv-popup 
      :show="showAlarmList" 
      mode="bottom" 
      @close="showAlarmList = false"
    >
      <view class="alarm-popup">
        <view class="popup-header">
          <text class="title">报警列表</text>
          <text class="close" @click="showAlarmList = false">✖️</text>
        </view>
        
        <view class="alarm-devices">
          <view 
            v-for="device in activeAlarms" 
            :key="device.deviceId"
            class="alarm-device"
          >
            <view class="device-title">
              <text class="name">{{ device.deviceName }}</text>
              <text class="id">{{ device.deviceId }}</text>
            </view>
            
            <view class="alarm-items">
              <view 
                v-for="(alarm, index) in device.alarms" 
                :key="index"
                :class="['alarm-item', alarm.type]"
              >
                <text class="alarm-icon">{{ alarm.type === 'error' ? '❌' : '⚠️' }}</text>
                <view class="alarm-content">
                  <text class="message">{{ alarm.message }}</text>
                  <text class="time">{{ alarm.time }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import StatusBar from '@/components/StatusBar/StatusBar.vue'
import { useDeviceStore } from '@/stores/device'
import uvPopup from '@/uni_modules/uv-ui/components/uv-popup/uv-popup.vue'
import uvOverlay from '@/uni_modules/uv-ui/components/uv-overlay/uv-overlay.vue'
import uvTransition from '@/uni_modules/uv-ui/components/uv-transition/uv-transition.vue'

// 注册组件
defineOptions({
  name: 'IndexPage',
  components: {
    StatusBar,
    'uv-popup': uvPopup,
    'uv-overlay': uvOverlay,
    'uv-transition': uvTransition
  }
})

const deviceStore = useDeviceStore()
const showFilterPopup = ref(false)
const showAlarmList = ref(false)
const searchText = ref('')
const filterPopupRef = ref(null)
const filters = ref({
  type: '',
  status: ''
})

// 设备类型选项
const deviceTypes = [
  { label: '全部', value: '' },
  { label: '天线类', value: 'antenna' },
  { label: '高频接收机类', value: 'receiver' },
  { label: '传输光端机类', value: 'optical' },
  { label: '保障设备类', value: 'support' }
]

// 设备状态选项
const deviceStatus = [
  { label: '全部', value: '' },
  { label: '正常', value: 'online' },
  { label: '警告', value: 'warning' },
  { label: '错误', value: 'error' },
  { label: '离线', value: 'offline' }
]

// 状态文本
const getStatusText = (status) => {
  const statusMap = {
    online: '正常',
    warning: '警告',
    error: '错误',
    offline: '离线'
  }
  return statusMap[status] || '未知'
}

// 筛选后的设备列表
const filteredDevices = computed(() => {
  let devices = deviceStore.devices

  // 搜索过滤
  if (searchText.value) {
    const searchLower = searchText.value.toLowerCase()
    devices = devices.filter(device => 
      device.name.toLowerCase().includes(searchLower) ||
      device.id.toLowerCase().includes(searchLower)
    )
  }

  // 类型过滤
  if (filters.value.type) {
    devices = devices.filter(device => device.type === filters.value.type)
  }

  // 状态过滤
  if (filters.value.status) {
    devices = devices.filter(device => device.status === filters.value.status)
  }

  return devices
})

// 报警相关
const hasActiveAlarms = computed(() => deviceStore.hasActiveAlarms)
const activeAlarms = computed(() => deviceStore.activeAlarms)

// 处理设备点击
const handleDeviceClick = (device) => {
  deviceStore.setCurrentDevice(device)
  uni.navigateTo({
    url: `/pages/device/device?id=${device.id}`
  })
}

// 处理筛选变更
const handleFilterChange = (key, value) => {
  if (filters.value[key] === value) {
    filters.value[key] = ''
  } else {
    filters.value[key] = value
  }
}

// 重置筛选
const resetFilters = () => {
  filters.value = {
    type: '',
    status: ''
  }
  searchText.value = ''
}

// 监听弹窗状态变化
watch(showFilterPopup, (newVal) => {
  console.log('Filter popup state changed:', newVal)
})

// 打开筛选弹窗
const openFilter = () => {
  console.log('Opening filter popup')
  filterPopupRef.value?.open()
}

// 关闭筛选弹窗
const closeFilter = () => {
  filterPopupRef.value?.close()
}

// 页面加载时获取设备列表
onMounted(() => {
  deviceStore.fetchDevices()
})

// 在 script setup 中添加 closeFilter 方法的引用
defineExpose({
  openFilter,
  closeFilter
})
</script>

<style lang="scss" scoped>
.container {
  padding-top: 88rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-bar {
  padding: 20rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.search-input {
  flex: 1;
  height: 72rpx;
  background-color: #ffffff;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  gap: 10rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

  .search-icon {
    font-size: 32rpx;
    color: #666666;
  }

  input {
    flex: 1;
    height: 100%;
    font-size: 28rpx;
  }

  .placeholder {
    color: #999999;
  }
}

.filter-btn {
  width: 72rpx;
  height: 72rpx;
  background: #ffffff;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

  &:active {
    opacity: 0.7;
  }
}

.alarm-banner {
  margin: 0 20rpx 20rpx;
  padding: 20rpx;
  background: #fff3e0;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
  color: #ff9800;
}

.device-list {
  padding: 0 20rpx;
}

.device-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.device-header {
  margin-bottom: 20rpx;
}

.device-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.device-name {
  font-size: 32rpx;
  font-weight: bold;
}

.status-tag {
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #ffffff;
}

.status-tag.online {
  background: #67C23A;
}

.status-tag.warning {
  background: #E6A23C;
}

.status-tag.error {
  background: #F56C6C;
}

.status-tag.offline {
  background: #909399;
}

.device-id {
  font-size: 28rpx;
  color: #666666;
}

.device-data {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.data-item {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 10rpx;
}

.data-item .label {
  font-size: 26rpx;
  color: #666666;
  margin-bottom: 10rpx;
  display: block;
}

.data-item .value {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.alarm-list {
  margin-bottom: 20rpx;
}

.alarm-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 10rpx;
  border-radius: 10rpx;
  margin-bottom: 10rpx;
}

.alarm-item.warning {
  background: #fdf6ec;
}

.alarm-item.error {
  background: #fef0f0;
}

.alarm-message {
  font-size: 28rpx;
  color: #333333;
}

.device-footer {
  display: flex;
  justify-content: flex-end;
}

.update-time {
  font-size: 24rpx;
  color: #999999;
}

.filter-popup {
  background: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.popup-header .title {
  font-size: 32rpx;
  font-weight: bold;
}

.popup-header .close {
  font-size: 32rpx;
  color: #999999;
  padding: 10rpx;
}

.filter-section {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 20rpx;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.filter-option {
  font-size: 28rpx;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  background: #f8f9fa;
  color: #666666;
}

.filter-option.active {
  background: #409EFF;
  color: #ffffff;
}

.reset-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background: #f8f9fa;
  color: #666666;
  border-radius: 40rpx;
  margin-top: 30rpx;
}

.alarm-popup {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;
  max-height: 80vh;
}

.alarm-devices {
  max-height: calc(80vh - 100rpx);
  overflow-y: auto;
}

.alarm-device {
  margin-bottom: 30rpx;
}

.device-title {
  margin-bottom: 20rpx;
}

.device-title .name {
  font-size: 32rpx;
  font-weight: bold;
  margin-right: 20rpx;
}

.device-title .id {
  font-size: 28rpx;
  color: #666;
}

.alarm-items {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.alarm-content {
  flex: 1;
}

.alarm-content .message {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.alarm-content .time {
  font-size: 24rpx;
  color: #999;
}
</style> 